-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
71 lines (59 loc) · 1.5 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
using namespace std;
// Definition of a tree node.
struct Node {
int data;
Node* left;
Node* right;
Node(int data) : data(data), left(nullptr), right(nullptr) {}
};
// Recursively build the tree using sentinel (-1).
Node* buildTree() {
int data;
cout << "Enter node value (-1 for no node): ";
cin >> data;
if (data == -1)
return nullptr;
Node* root = new Node(data);
cout << "Enter left child of " << data << ":\n";
root->left = buildTree();
cout << "Enter right child of " << data << ":\n";
root->right = buildTree();
return root;
}
// Inorder traversal: Left, Root, Right.
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
// Preorder traversal: Root, Left, Right.
void preorder(Node* root) {
if (root != nullptr) {
cout << root->data << " ";
preorder(root->left);
preorder(root->right);
}
}
// Postorder traversal: Left, Right, Root.
void postorder(Node* root) {
if (root != nullptr) {
postorder(root->left);
postorder(root->right);
cout << root->data << " ";
}
}
int main() {
cout << "Build the binary tree:\n";
Node* root = buildTree();
cout << "\nInorder Traversal: ";
inorder(root);
cout << "\nPreorder Traversal: ";
preorder(root);
cout << "\nPostorder Traversal: ";
postorder(root);
cout << endl;
return 0;
}